﻿using NineApi.Responses;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace NineApi.Utils
{
    public class Sign
    {
        public static string SignObj<TObj>(TObj obj,string key)
        {
            var type = typeof(TObj);
            var props=type.GetProperties().OrderBy(x=>x.Name);
            string res = "";
            List<string> temp = new List<string>();
            foreach (var prop in props)
            {
                var name = prop.Name.ToLower();
                if (name== "sign" || name== "sign_type") continue;
                var value = prop.GetValue(obj);
                if (value == null) continue;
                temp.Add($"{name}={value}");
            }
           res= string.Join("&", temp);

            var md5Hash = GetMd5Hash(res+key); // 获取 MD5 哈希值
            return md5Hash;
        }

       private   static string GetMd5Hash(string input)
        {
            using (MD5 md5Hash = MD5.Create())
            {
                byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));

                StringBuilder sBuilder = new StringBuilder();
                for (int i = 0; i < data.Length; i++)
                {
                    sBuilder.Append(data[i].ToString("x2"));
                }

                return sBuilder.ToString();
            }
        }

        private   static bool VerifyMd5Hash(string input, string hash)
        {
            using (MD5 md5Hash = MD5.Create())
            {
                string hashOfInput = GetMd5Hash(input);

                StringComparer comparer = StringComparer.OrdinalIgnoreCase;

                if (0 == comparer.Compare(hashOfInput, hash))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
    }
}
